package com.uex.dev.manage.admin.utils;

import com.uex.dev.manage.admin.enums.PortalTypeEnum;
import com.uex.dev.manage.admin.intercepter.UserContext;
import com.uex.dev.manage.admin.po.GuestLogPO;
import com.uex.dev.manage.admin.po.UserLogPO;
import com.uex.dev.manage.admin.service.IGuestLogService;
import com.uex.dev.manage.admin.service.IUserLogService;
import io.micrometer.common.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @author lzs
 * @create 2024/03/07
 * @description
 */

public class LogUtil {

    private static IGuestLogService guestLogService;
    private static IUserLogService userLogService;
    private static String openid;
    private static String agent;

    public static void setLog(IGuestLogService guestLog, IUserLogService userLog, String _agent, String _openid) {
        guestLogService = guestLog;
        userLogService = userLog;
        openid = _openid;
        agent = _agent;
    }

    public static void log(Integer deviceId, String Operation) {
        PortalTypeEnum portal;
        if (agent.contains("Windows") || agent.contains("Macintosh")) {
            portal = PortalTypeEnum.PLATFORM;
        } else if (agent.contains("Android") || agent.contains("iPhone") || agent.contains("iPad")) {
            portal = PortalTypeEnum.APP;
        } else portal = PortalTypeEnum.APPLET;

        if (StringUtils.isNotBlank(openid)) {
            GuestLogPO guestLog = new GuestLogPO();
            guestLog.setLogWxid(openid);
            guestLog.setLogDevid(deviceId);
            guestLog.setLogTime(LocalDateTime.now());
            guestLog.setLogOp(Operation);
            guestLogService.save(guestLog);
        } else {
            UserLogPO userLog = new UserLogPO();
            userLog.setLogUserid(UserContext.getUserInfoLocal().getId());
            userLog.setLogDevid(deviceId);
            userLog.setLogTime(LocalDateTime.now());
            userLog.setLogPortal(portal);
            userLog.setLogOp(Operation);
            userLogService.save(userLog);
        }
    }
}

